﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ServiceStack.Redis;

namespace CloudPms.Common.CacheProvider
{
    /// <summary>
    /// 中央缓存初始化
    /// <para>--------------------------</para>
    /// <para>@Author: cnalexi@gmail.com</para> 
    /// <para>@Create: 2012/10/12</para> 
    /// </summary>
    public class CenterCacheInit
    {
        private const string CENTER_CACHE_KEY = "YQ7PR-QTHDM-HCBCV-9GKGG-TB2TM";

        private static PooledRedisClientManager pm = PooledManager.Instance.GetPooledClientManager();

        private const string START = "S",COMPLETE="C";

        public static bool CanStartCreating()
        {
            try
            {
                using (var client = pm.GetCacheClient())
                {
                    var status = client.Get<string>(CENTER_CACHE_KEY); //获取RedisCacheClient

                    if (!string.IsNullOrWhiteSpace(status)) return false;

                    client.Set(CENTER_CACHE_KEY, START); //存入RedisCacheClient
                }
            }catch
            {
                return false;
            }

            return true;
        }

        public static bool IsComplete()
        {
            using (var client = pm.GetClient())
            {
                var status = client.Get<string>(CENTER_CACHE_KEY);

                if (status==COMPLETE) return true;
            }

            return false;
        }

        public static void Complete()
        {
            using (var client = pm.GetCacheClient())
            {
                var status = client.Get<string>(CENTER_CACHE_KEY); 

                if (status==START) client.Set(CENTER_CACHE_KEY,COMPLETE);
            }
        }

        public static bool ReStart()
        {
            using (var client = pm.GetCacheClient())
            {
                var status = client.Get<string>(CENTER_CACHE_KEY); //获取RedisCacheClient

                if (status == COMPLETE)
                {
                    //存入RedisCacheClient
                    if (client.Set(CENTER_CACHE_KEY, string.Empty))
                    {
                        return true;
                    }
                }

                return false;
            }
        }
        
    }

    
}
